﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Common
{
    public class FileHelper
    {
        static public Byte[] ReadAllByte(string fileFullPath)
        {
            System.IO.FileStream fs = System.IO.File.OpenRead(fileFullPath);

            if (fs.CanRead)
            {
                byte[] fileContent = new byte[fs.Length];

                fs.Read(fileContent, 0, (int)fs.Length);
                fs.Flush();
                fs.Close();

                return fileContent;
            }
            else
                return null;
        }

        static public string ReadAllText(string fileFullPath)
        {
            byte[] fileContent = ReadAllByte(fileFullPath);

            if(null != fileContent)
            {
                return fileContent.GetString();
            }
            else
                return "";
        }

        static public void WriteAllByte(string fileFullPath, byte[] fileContent)
        {
            System.IO.FileStream fs = System.IO.File.Create(fileFullPath);

            if (fs.CanWrite)
            {
                fs.Write(fileContent, 0, fileContent.Length);
                fs.Flush();
                fs.Close();
            }
        }

        static public void WriteAllText(string fileFullPath, string fileContent)
        {
            WriteAllByte(fileFullPath, fileContent.GetBytes());
        }

        static public void AppendLine(string fileFullPath, string fileContent)
        {
            string newContent = ReadAllText(fileFullPath);

            if (newContent.Length < 2 || newContent.Substring(newContent.Length - 2).Equals(Environment.NewLine))
                newContent += fileContent + Environment.NewLine;
            else
                newContent += Environment.NewLine + fileContent + Environment.NewLine;

            System.IO.FileStream fs = System.IO.File.Create(fileFullPath);

            if (fs.CanWrite)
            {
                byte[] fileByte = newContent.GetBytes();
                fs.Write(fileByte, 0, fileByte.Length);
                fs.Flush();
                fs.Close();
            }
        }
    }
}
